package org.mao.parser;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.mao.forum.entity.ForumPost;
import org.mao.forum.entity.ForumTask;
import org.mao.forum.enums.ForumTaskEnum.ForumEnum;
import org.mao.forum.vo.ForumTaskParamsVo;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

@Component
public class ForumParserProxy {

	private static Logger logger = Logger.getLogger(ForumParserProxy.class);

	@Resource(name = "SisForumPageParser")
	private IForumPageParser sisForumPageParser;

	@Resource(name = "LwgodForumPageParser")
	private IForumPageParser lwgodForumPageParser;

	public IForumPageParser getForumPageParser(Integer forumId) {
		if (ForumEnum.SIS.equals(forumId)) {
			return sisForumPageParser;
		} else if (ForumEnum.LWGOD.equals(forumId)) {
			return lwgodForumPageParser;
		}
		throw new RuntimeException("can not find forum parser");
	}

	public void scan(ForumTask forumTask, ForumTaskParamsVo paramsVo) {
		IForumPageParser forumPageParser = this.getForumPageParser(forumTask.getForumId());
		List<Integer> sections = null;
		if (paramsVo != null && CollectionUtils.isNotEmpty(paramsVo.getSections())) {
			sections = paramsVo.getSections();
			this.scan(forumPageParser, sections, paramsVo);
		} else {
			sections = Lists.newArrayList();
			sections.add(forumTask.getSectionId());
			this.scan(forumPageParser, sections, paramsVo);
		}
	}
	
	public void reReadTorrentUrl(Integer forumId, ForumPost forumPost) {
		IForumPageParser forumPageParser = this.getForumPageParser(forumId);
		forumPageParser.readAttarch(forumPost);
	}
	
	public List<String> reReadImageList(Integer forumId, ForumPost forumPost) {
		IForumPageParser forumPageParser = this.getForumPageParser(forumId);
		return forumPageParser.readImageList(forumPost);
	}

	private void scan(IForumPageParser forumPageParser, List<Integer> sections, ForumTaskParamsVo paramsVo) {
		try {
			for (Integer sectionId : sections) {
				List<String> sectionList = forumPageParser.readSectionList(sectionId, paramsVo);
				Thread.sleep(1000);
				for (String sectionUrl : sectionList) {
					List<ForumPost> postList = forumPageParser.readSisPostList(sectionUrl, sectionId);
					Thread.sleep(1000);
					for (ForumPost forumPost : postList) {
						forumPageParser.readPost(forumPost);
						Thread.sleep(1000);
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
